//
//  MCNewMarketingAddGoodsViewController.swift
//  StoreManage
//
//  Created by MC on 2018/6/27.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

typealias MCNewMarketingAddGoodsViewControllerClosure = (NSMutableArray) -> Void

class MCNewMarketingAddGoodsViewController: MCViewController {
    
    
    public var clousre : MCNewMarketingAddGoodsViewControllerClosure?
    
    public var pageNumber = 1
    
    
    private var keyWord = "" // 搜索关键字
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking(keyWord: keyWord)
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Action
    @objc func selectedAllButtonClicked() {
        bottomView.selectedAllButton.isSelected = !bottomView.selectedAllButton.isSelected
        for model in dataArrayM {
            (model as! MCNewMarketingAddGoodsModel).isSelected = bottomView.selectedAllButton.isSelected
        }
        self.tableView.reloadData()
    }
    
    @objc func batchButtonClicked() {
        let array = NSMutableArray()
        for model in dataArrayM {
            if (model as! MCNewMarketingAddGoodsModel).isSelected {
                array.add((model as! MCNewMarketingAddGoodsModel))
            }
        }
        if array.count == 0 {
            MCHUD_text(message: "请选择商品", view: self.view, delay: 1.2)
            return
        }
        
        clousre?(array)
        // 传值回上个页面
        self.navigationController?.popViewController(animated: true)
    }
    
    // MARK: - Network
    func sendNetworking(keyWord:String) {
        let para = [
            "pageNum" : pageNumber,
            "keyWord" : keyWord
            ] as [String : Any]

        MCNetwork_post(url: JAVA_findGoodsOfStore, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in

            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()

            if self.pageNumber == 1 {
                self.dataArrayM.removeAllObjects()
            }

            let dataArray = response["data"] as? NSArray ?? []

            if self.dataArrayM.count + dataArray.count == 0 {
                self.tableView.showBgImage()
            } else {
                self.tableView.hideBgImage()
                for dict in dataArray {
                    let model = MCNewMarketingAddGoodsModel()
                    model.setValuesForKeys(dict as? [String:Any] ?? [:])
                    self.dataArrayM.add(model)
                }
            }

            self.tableView.reloadData()


        }, dislike: { (response) in }) { (error) in }
    }
    

    
    // MARK: - Method
    func baseSetting() {
        title = "店铺商品"
        self.view.backgroundColor = UIColor.white
        
        navigationBarLineHidden = true
        
        self.tableView.mj_header = MCRefreshHeader.init(refreshingBlock: {
            self.pageNumber = 1
            self.sendNetworking(keyWord: self.keyWord)
        })
        
        self.tableView.mj_footer = MCRefreshFooter.init(refreshingBlock: {
            self.pageNumber += 1
            self.sendNetworking(keyWord: self.keyWord)
        })
    }
    
    func initUI() {
        
        view.addSubview(searchTextField)
        searchTextField.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(20)
            make.top.equalTo(0)
            make.size.equalTo(CGSize.init(width: MCScreenWidth - 40, height: 30))
        }

        
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(40, 0, 50, 0))
        }
        
        view.addSubview(bottomView)
        bottomView.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(50)
        }
        
        
    }
    
    // MARK: - Setter & Getter
    private lazy var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
        return tableView
    }()
    
    private lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()

    private lazy var searchTextField: MCTextFiled = {
        let tf = MCTextFiled()
        tf.backgroundColor = UIColor.MCGray_light
        tf.layer.cornerRadius = 15
        tf.layer.masksToBounds = true
        tf.clearButtonMode = .always
        tf.placeholder = "请输入商品名字"
        tf.delegate = self
        tf.returnKeyType = UIReturnKeyType.search
        
        let imageView = UIImageView()
        imageView.image = #imageLiteral(resourceName: "Reuse_search_spacing")
        imageView.frame = CGRect.init(x: 0, y: 0, width: 23, height: 13)
        tf.leftView = imageView
        tf.leftViewMode = .always
        return tf
    }()

    
    
    private lazy var bottomView: MCChooseForPlatformBottomView = {
        let view = MCChooseForPlatformBottomView()
        view.batchButton.setTitle("确认添加", for: .normal)
        view.selectedAllButton.addTarget(self, action: #selector(selectedAllButtonClicked), for: UIControlEvents.touchUpInside)
        view.batchButton.addTarget(self, action: #selector(batchButtonClicked), for: UIControlEvents.touchUpInside)
        
        return view
    }()

    
    public lazy var selectedGoodsArray: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()

}

extension MCNewMarketingAddGoodsViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCNewMarketingAddGoodsCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.model = self.dataArrayM[indexPath.row] as! MCNewMarketingAddGoodsModel
        return cell
    }
    
}


extension MCNewMarketingAddGoodsViewController : UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    
        textField.resignFirstResponder()
        
        keyWord = textField.text ?? ""
        pageNumber = 1
        
        self.sendNetworking(keyWord: self.keyWord)

        return true
    }
    
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
      
        keyWord = ""
        pageNumber = 1
        
        self.sendNetworking(keyWord: self.keyWord)
        return true
    }
}









